<?php
namespace app\controller;

use app\BaseController;
use app\model\SpecItem as SPI;
use app\model\Spec as SP;
use think\validate\ValidateRule;
use think\facade\Session;

class SpecItem extends BaseController
{
    protected $middleware = [
        // 对所有方法有效
        '\app\middleware\NavCheck',
        '\app\middleware\UrlCheck',
        '\app\middleware\LoginCheck',
    ];
    public function index($spac_id)
    {
        $list = SP::where('id', $spac_id)
            ->find();
        //var_dump($list->toArray());

        return view("/specitem/index",["list"=>$list]);
    }

    public function data()
    {
        $limit = $this->request->param('limit');
        $page = $this->request->param("page");

        $offset = ($page-1)*$limit;
        $spec_id = $this->request->get("id");
        $list = SPI::where('spec_item.spec_id', $spec_id)
            ->leftJoin("spec","spec_item.spec_id=spec.id")
            ->limit($offset,$limit)
            ->field("spec_item.*,spec.spec_name")
            ->select();
        $count = SPI::where('spec_id', $spec_id)->count();

        return json([ "code"=>0,"msg"=>"查询成功","count"=>$count,"data"=>$list]);
    }

    public function add($spec_id){
        if($this->request->isPost()){
            $data = $this->request->post();
            $user = new SPI();
            $res = $user->save($data);

            if($res){
                $this->success("规格值添加成功","/Specitem/index/spac_id/".$data['spec_id']);
            }
            $this->error("规格值添加失败");
        }

        $list = SP::where('id', $spec_id)->find();
        return view("",["list"=>$list]);
    }

    public function update($id){

        $list = SPI::alias('spi')
            ->leftJoin("spec s","s.id=spi.spec_id")
            ->where('spi.id', $id)
            ->field('s.spec_name,spi.*')
            ->find()
            ->getData();

        return view("add",['list'=>$list]);
    }

    public function del($id){
        $user = SPI::find($id);
        $res = $user->delete();
        if($res){
            return json(["code"=>0,"msg"=>"删除成功"]);
        }
        return json(["code"=>400,"msg"=>"删除失败"]);
    }
}